#include "bsp_Par.h"
#include <string.h>


_Sys_t  Sys;

#define SECTOR_SIZE           1024    		//内部FLASH页大小
#define SYS_SLAVE_ADD 				0x0800F000 	//保存数据的位置  第64KB 位置


//从指定地址读取 16位
uint16_t FLASH_ReadHalfWord(uint32_t address)
{
  return *(__IO uint16_t*)address; 
}

//从FLASH中读取全字 32位
uint32_t FLASH_ReadWord(uint32_t address)
{
  uint32_t temp1,temp2;
  temp1=*(__IO uint16_t*)address; 
  temp2=*(__IO uint16_t*)(address+2); 
  return (temp2<<16)+temp1;
}
//从FLASH中连续读取多个数据
void FLASH_ReadMoreData(uint32_t startAddress,uint16_t *readData,uint16_t countToRead)
{
  uint16_t dataIndex;
  for(dataIndex=0;dataIndex<countToRead;dataIndex++)
  {
    readData[dataIndex]=FLASH_ReadHalfWord(startAddress+dataIndex*2);
  }
}
//从指定指定写入多个数据
void FLASH_WriteMoreData(uint32_t startAddress,uint16_t *writeData,uint16_t countToWrite)
{
	uint32_t PageError = 0;
	FLASH_EraseInitTypeDef f;

  if(startAddress<FLASH_BASE||((startAddress+countToWrite*2)>=(FLASH_BASE+1024*256)))
  {
    return;//非法地址
  }
  HAL_FLASH_Unlock();         //开锁
  uint32_t offsetAddress=startAddress-FLASH_BASE;               //从基地址开始
  uint32_t sectorPosition=offsetAddress/SECTOR_SIZE;            //确定每页大小
  
  uint32_t sectorStartAddress=sectorPosition*SECTOR_SIZE+FLASH_BASE;    //确定地址
	
	f.TypeErase = FLASH_TYPEERASE_PAGES;
	f.PageAddress = sectorStartAddress;
	f.NbPages = 1;
	
  HAL_FLASHEx_Erase(&f, &PageError);//擦除扇区
  
  uint16_t dataIndex;
  for(dataIndex=0;dataIndex<countToWrite;dataIndex++)
  {
		HAL_FLASH_Program_IT(FLASH_TYPEPROGRAM_WORD ,sectorStartAddress,writeData[dataIndex]);
  }
  
  HAL_FLASH_Lock();//上锁
}


//=============================================================================
//文件名称：Sys_Ref
//功能概要：数据更新,从Flash中读取数据
//参数说明：无
//函数返回：无
//=============================================================================
void Sys_Ref()
{
	uint16_t buff[sizeof(_Sys_t)];
//	printf("Sys_Ref..\r\n");
	//获取保存在系统中的参数
	memset(&Sys,0,sizeof(_Sys_t));
	FLASH_ReadMoreData(SYS_SLAVE_ADD,buff,sizeof(_Sys_t));
	memcpy(&Sys,buff,sizeof(_Sys_t));
}
//=============================================================================
//文件名称：Sys_Save
//功能概要：保存数据，将最新的数据保存到FLASH中
//参数说明：无
//函数返回：无
//=============================================================================
void Sys_Save()
{
		uint16_t buff[sizeof(_Sys_t)];
		//保存参数
		memcpy(buff,&Sys,sizeof(_Sys_t));
		//保存到FLASH中
		FLASH_WriteMoreData(SYS_SLAVE_ADD,buff,sizeof(_Sys_t));

}